package apache.httpclient;

import java.util.Iterator;
import java.util.Map;

import com.ning.http.client.AsyncCompletionHandler;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.AsyncHttpClientConfig;
import com.ning.http.client.AsyncHttpClientConfig.Builder;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Response;

public class HttpRequestUtil {
		private static final AsyncHttpClient asyncHttpClient;
		static {
			Builder builder = new AsyncHttpClientConfig.Builder();
			builder.setConnectionTimeoutInMs(1000 * 8);

			int total = 10000;
			String str = "3000";
			if (isNotEmpty(str)) {
				total = new Integer(str);

			}
			
			String pooltimeoutStr = "120000";
			String timeoutStr = "60000";
			String retimeoutStr = "60000";
			String websockettimeoutStr = "900000";
			String hostStr = "1000";
			int pooltimeout=60 * 1000;
			int timeout=60 * 1000;
			int retimeout=60 * 1000;
			int websockettimeout =15 * 60 * 1000;
			int host=1000;
			if (isNotEmpty(pooltimeoutStr)) {
				pooltimeout = new Integer(pooltimeoutStr);

			}
			if (isNotEmpty(timeoutStr)) {
				timeout = new Integer(timeoutStr);

			}
			if (isNotEmpty(retimeoutStr)) {
				retimeout = new Integer(retimeoutStr);

			}
			if (isNotEmpty(websockettimeoutStr)) {
				websockettimeout = new Integer(websockettimeoutStr);

			}
			if (isNotEmpty(hostStr)) {
				host = new Integer(hostStr);

			}
	        builder.setIdleConnectionInPoolTimeoutInMs(pooltimeout);
	        builder.setIdleConnectionTimeoutInMs(timeout);
	        builder.setMaximumConnectionsPerHost(host);
	        builder.setRequestTimeoutInMs(retimeout);
	        builder.setWebSocketIdleTimeoutInMs(websockettimeout);
			builder.setMaximumConnectionsTotal(total);
			AsyncHttpClientConfig asyncHttpClientConfig = builder.build();
			asyncHttpClient = new AsyncHttpClient(asyncHttpClientConfig);
		}
	
		public static void main(String[] args) {
			 //String sendurl = "http://10.101.10.47:18022/mixlist.do?msisdn=13632664097";
			 //String jsonStr = "{\"Source\":\"MM\",\"Fields\":["ACTIVITYNAME","PREVIEWPICTURE1","USERMONTHLYTYPE","SUBTYPE","UPDATEDATE","SERVTYPE","USAGE_DESC","ACTIVITYICONURL","M_REWARD_PACKAGE_E","PICTURE4","FREE_ZONE","LOGO1","FY_PRIVILEGE_RULE","DEVICE_ID","SOURCE","WWWPROPAPICTURE3","HE_BIG_CONTENT_SLOGAN","ACTIVITYDESC","PICURL","PRICETYPE","FREE_LID_RECOMMEND_PIC","XTYPE","PROSUBMITDATE","FY_AWARD_STATE","TRY_PLAY_ORIENTATION","LOGO4","M_REWARD_RULE","PROGRAMID","SCREEN_URL4","PREVIEWPICTURE2","BEGIN_TIME","FREE_LID_RECOMMEND_DESC","LOGO_URL","M_REWARD_ID","FY_COMMENT","SCREEN_URL2","M_REWARD_QUERY_ID","PRICETYPE","VERSIONNAME","PACKAGE_URL","CARDRULE","SCREEN_URL1","CARDBUTTONTEXT","CONTENTID","CARDPARAMS","PKGNAME","VERSIONDESC","TWICENAME","AVERAGEMARK","HOTSCORE","MMCONTENTID","FY_AWARD_CONTENT","LUPDDATE","SCREEN_URL3","CHARGETYPE","M_NAME","MH_PHOTO","ITEMMARK","ISMMTOEVENT","PRICE","CHARGETIME","ACTION","CARDPICURL","INTRODUCTION","APPSIZE","PROVIDER","SPNAME","MOURL","COPYRIGHTFLAG","LOGO6","SIGNATURE","APP_DESCRIPTION","CATENAME","DOWNLOAD_NUM","PICTURE1","CLIENTID","PACKAGENAME","FY_AWARD_ADDRESS","GRADE1_TYPE","GOODSID","ACTIVITYDETAILURL","AP_NAME","CARDTYPE","HE_BIG_CONTENT_NAME","APP_B_SLOGAN2","HE_BIG_CONTENT_JUMPURL_MO","NOTICE","APP_B_SLOGAN1","MATCH","CARDRULEID","FY_ICON","DESCRIPTION","LOGO3","VERSIONCODE","END_TIME","M_DESC","M_REWARD_VID","PID","PROGRAMSIZE","HE_BIG_CONTENT_PICURL","FY_PRIVILEGE_NAME","TRY_PLAY_DEMOKEY","NAME","VERSION","CDNURL","LOGO","MARKTEXT","ISACTIVITY","GRADE2_TYPE","APP_SPECIALDESC","APPCATENAME","PLATFORM","FLAG","LOGO2","VERSIONNAME","CONTENT_DESC","PICTURE2","PICTURE3","ISCDN"],"Parentid":"x3418","Sorttype":"sortid_desc","Portal":"M","Appname":"MM5.2.0.001.01_CTAndroid_JT","QueryPage":1,"Ispage":0,"Deviceid":"512","RecordsPage":10,"CFields":["DESCS","CATEGORY_PIC","CARDMORETEXT","ANDGAME_LOGO","STARTTIME","ANDGAME_LOGO_ADURL","IS_MMINFO","M_ISMONTHLY","HE_BIG_ACTIVITY_LOGO","WP_TYPE","ID","CARDDIVIDELINE","CARDMOREURL2","CARDITEMSUM","CARDMORETEXT2","ISSHOWZONE","CARDVERSION","DESCS_EXT","MM_INDEX","COUNTLIMIT","CARDID","NAME","CARDMOREURL","VIDEONEW_TYPE","FY_1111_TOTAL","PICURL","SPECIAL_APPSTR","APPNAME","ENDTIME","CARDSHOWNEW","BUTTONPICURL","LOGOURL","BGPICURL","SPECIAL_DESC","CHANGEDATE","POPUPID","WP_BANNERURL","CARDTYPE","BUTTONPICJUMPURL","FY_1111_INFO","THEMATICURL_A","SPECIAL_PIC","BGPICJUMPURL","NODETYPE","SPECIALBADGELIST","CARDNEEDLOGIN","POPUPRULE","ICONID","MONTHLY_TYPE_URL","POPUPPARAMTER","CATEGORYID","APPCATENAME","EXTCATEGORYPRO"],\"Isfilter\":-1}";
			 String sendurl = "http://10.1.5.50:8787/web/ca.do";
			 String jsonStr = "{\"ids\":[{\"id\":\"16318569_0\",\"result\":\"3\"},{\"id\":\"16318572_0\",\"result\":\"3\"}]}";
			 String jsonString=
					 HttpRequestUtil.postXML(sendurl,jsonStr,"UTF-8", null);
			 System.out.println(jsonString);
		}
	
		public static final boolean isNotEmpty(String foo) {

	        return (null != foo && foo.trim().length() > 0);
	    }
		
		public static String postXML(String strURL, String xml,
				final String encode, Map<String, String> headers) {
			try {
				BoundRequestBuilder post = asyncHttpClient.preparePost(strURL);
				post
						.setHeader("Content-Type", "application/json;charset="
								+ encode);

				if (headers != null) {
					Iterator<String> keys = headers.keySet().iterator();
					while (keys.hasNext()) {
						String key = keys.next();
						if (key != null && key.trim().length() > 0) {
							String value = headers.get(key);
							if (value != null && value.trim().length() > 0) {
								post.setHeader(key, value);
							}
						}
					}
				}
				post.setBodyEncoding(encode);
				post.setBody(xml);
				ListenableFuture<String> execute = post
						.execute(new AsyncCompletionHandler<String>() {
							@Override
							public String onCompleted(Response response)
									throws Exception {
								return response.getResponseBody(encode);
							}
						});
				
				return execute.get();
			} catch (Exception e) {
				throw new RuntimeException("post con error");
			}
		}
}
